package com.demo.datastructure.linkedList;


/**
 * @description: 链表合并
 * @author: ljr
 * @time: 2021/4/14 17:41
 */
public class LinkedListMergeDemo6 {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0, null);
        ListNode prev = head;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                prev.next = l1;
                prev = prev.next;
                l1 = l1.next;
            }else{
                prev.next = l2;
                prev = prev.next;
                l2 = l2.next;
            }
            prev.next = null;
        }

        prev.next = l1 == null ? l2 :  l1;
        ListNode old = head;
        head = head.next;
        old.next = null;
        return head;
    }

    public ListNode reverseLinkedList(ListNode l1) {
        if(l1.next == null){
            return l1;
        }

        ListNode head = reverseLinkedList(l1.next);
        l1.next.next = l1;
        l1.next = null;
        return head;

        //return reverseLinkedList(l1, null);
    }

    public ListNode reverseLinkedList(ListNode l1,  ListNode prev) {
        if(l1.next == null){
            l1.next = prev;
            return l1;
        }else{
            ListNode next = l1.next;
            l1.next = prev;
            return reverseLinkedList(next, l1);
        }
    }



    public static void main(String[] args) {
        LinkedListMergeDemo6 linkedListDemo4 = new LinkedListMergeDemo6();
        ListNode l5 = new ListNode(5, null);
        ListNode l4 = new ListNode(4, l5);
        ListNode l3 = new ListNode(3, l4);
        ListNode l2 = new ListNode(2, l3);
        ListNode l1 = new ListNode(1, l2);

        ListNode node = linkedListDemo4.reverseLinkedList(l1);
        System.out.println(node);
    }


}
